﻿using System;
using System.Collections.Generic;
using System.Threading;
using System.Windows.Forms;
using WUTOS.DataBase.DataBaseDAL;

namespace WUTOS.DataBase
{
    public partial class MsSqlCfgTools : Form
    {
        #region -变量-
        
        DataBaseInfo databaseModel = new DataBaseInfo();

        private delegate void InitialControl(string text);

        static AutoResetEvent autoEvent;

        #endregion
        
        public MsSqlCfgTools()
        {
            InitializeComponent();
            autoEvent = new AutoResetEvent(false);
        }

        private void tslOption_Click(object sender, EventArgs e)
        {
            OptionFrame optionFrame = new OptionFrame();
            if (optionFrame.ShowDialog()==DialogResult.OK)
            {
                string localhostName = optionFrame.EighneName;
                UppDateMsg(optionFrame.ServerResetInfor);
                if (!localhostName.ToUpper().Contains("EXPRESS"))
                {
                   txtDbSource.Text="localhost";
                }
                else
                {
                   txtDbSource.Text=@"localhost\SQLEXPRESS";
                }
                this.Text = "数据库配置" + localhostName;
            }
        }
 
        /// <summary>
        /// 连接测试 开线程监测  解决主界延时
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnConnectTest_Click(object sender, EventArgs e)
        {
            txtScript.Text = "";
            this.errorProvider.Clear();
            if (!IsBlank())
            {
                 UppDateMsg("正在连接测试");
                 this.btnConnectTest.Enabled = false;
                 this.Cursor = Cursors.WaitCursor;
                 GetDataBaseInfo("master");
                 Thread threadConn = new Thread(new ThreadStart(ConnTest));
                 threadConn.Start();
                 autoEvent.WaitOne();
                 this.btnConnectTest.Enabled = true;
                 this.Cursor = Cursors.Arrow;
            }
        }

        /// <summary>
        /// 线程处理连接
        /// </summary>
        private void ConnTest()
        {
            string msg = "";
            if (BLL.ConnectionTest(2, databaseModel, ref msg))
            {
                BindDatabase();
                autoEvent.Set();
                UppDateMsg("连接测试成功");
            }
            else
            {
                autoEvent.Set();
                UppDateMsg(msg);
            }
        }

        private void GetDataBaseInfo(string InitialCatalog)
        {
            databaseModel.DataBaseSourse = txtDbSource.Text.Trim();
            databaseModel.InitialCatalog = InitialCatalog.Trim();
            databaseModel.UserID = txtAdminAccount.Text.Trim();
            databaseModel.PassWord = txtAdminPwd.Text.Trim();
            databaseModel.ConnectTimeout = 10;
            databaseModel.IntegratedSecurity = true;
        }

        /// <summary>
        /// 验证控件输入数据
        /// </summary>
        /// <returns></returns>
        private bool IsBlank()
        {
            if (txtDbSource.Text.Trim() == "")
            {
                this.errorProvider.SetError(this.txtDbSource, "请输入服务器名");
                this.ActiveControl = this.txtDbSource;
                return true;
            }
            if (txtAdminAccount.Text.Trim() == "")
            {
                this.errorProvider.SetError(this.txtAdminAccount, "请输入用户名");
                this.ActiveControl = this.txtAdminAccount;
                return true;
            }
            if (txtAdminPwd.Text.Trim() == "")
            {
                this.errorProvider.SetError(this.txtAdminPwd, "请输入密码");
                this.ActiveControl = this.txtAdminPwd;
                return true;
            }
            return false;
        }

        private void BindDatabase()
        {
            string temp = "";
            List<DataBaseInfo.Database> databaselist = BLL.GetSqlServerDataBaseInfo(2, databaseModel, ref temp);
            List<string> dbnamelist = new List<string>();
            foreach (DataBaseInfo.Database db in databaselist)
            {
                dbnamelist.Add(db.databasename);
            }
            cmbDbName.DataSource = dbnamelist;
        }

        /// <summary>
        /// 生成数据库脚本 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnCreateDB_Click(object sender, EventArgs e)
        {
            this.errorProvider.Clear();
            if (!IsBlank())
            {
                if (txtScript.Text == "")
                {
                    this.errorProvider.SetError(btnBrowse, "请选择脚本");
                    return;
                }
                if (cmbDbName.Text == "")
                {
                    this.errorProvider.SetError(cmbDbName, "请输入数据库名称");
                    return;
                }

                DataBaseDAL.DAL.ClearAllPool();
                UppDateMsg("开始生成数据库");
                GetDataBaseInfo(cmbDbName.Text);
                this.Cursor = Cursors.WaitCursor;
                this.btnCreateDB.Enabled = false;
                Thread threadConn = new Thread(new ParameterizedThreadStart(CreateDB));
                threadConn.Start(cmbDbName.Text);
                autoEvent.WaitOne();
                this.btnCreateDB.Enabled = true;
                this.Cursor = Cursors.Arrow;
            }
        }

        /// <summary>
        /// 生成数据库
        /// </summary>
        /// <param name="obj"></param>
        private void CreateDB(object obj)
        {
            string msg = "";
            if (CreateDateBase(2, databaseModel, txtScript.Text, "", ref msg,obj.ToString()))
            {
                autoEvent.Set();
                UppDateMsg("生成数据库成功");
            }
            else
            {
                autoEvent.Set();
                UppDateMsg("生成数据库失败:" + msg);
            }
        }

        private void btnBrowse_Click(object sender, EventArgs e)
        {
            ofdScript.Filter = "数据库脚本(*.sql)|*.sql";
            ofdScript.InitialDirectory = System.Environment.CurrentDirectory;

            if (ofdScript.ShowDialog() == DialogResult.OK)
            {
                if (ofdScript.CheckFileExists)
                {
                    this.errorProvider.Clear();
                    txtScript.Text = ofdScript.FileName;
                    string ScriptFileName = txtScript.Text.Substring(txtScript.Text.LastIndexOf("\\") + 1);
                    this.cmbDbName.Text = ScriptFileName.Remove(ScriptFileName.LastIndexOf("."));
                }
                else
                {
                    MessageBox.Show("该脚本不存在");
                    return;
                }

            }
        }

        private bool CreateDateBase(int loginmode, DataBaseInfo databasemodel, string scriptname, string savepath, ref string errormsg,string dbName)
        {
            string databasename = dbName;
            bool test = DataBaseDAL.BLL.IsDataBaseExist(loginmode, databasemodel, ref errormsg);
            if (test)
            {
                if (MessageBox.Show("数据库" + databasename + "存在，是否删除？","系统提示",
                    MessageBoxButtons.YesNo,MessageBoxIcon.Warning) == DialogResult.Yes)
                {
                    test = DataBaseDAL.BLL.DeleteDataBase(loginmode, databasemodel, ref errormsg);
                    if (!test)
                        return false;
                }
                else
                {
                    return false;
                }
            }
            databasemodel.InitialCatalog = databasename;
            return DataBaseDAL.BLL.CreateDataBaseByScript(loginmode, databasemodel, scriptname, savepath, ref errormsg);
        }
 
        /// <summary>
        /// 备份数据库
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnBackUpDB_Click(object sender, EventArgs e)
        {
            if (cmbDbName.Text == "")
            {
                MessageBox.Show("请先进行连接测试，获取数据库信息","系统提示",
                    MessageBoxButtons.OK,MessageBoxIcon.Information);
                return;
            }
            if (!IsBlank())
            {
                string msg = "";
                string backupPath = "";
                GetDataBaseInfo(cmbDbName.Text);

                DataBaseDAL.DAL.ClearAllPool();

                UppDateMsg("开始检测数据库是否存在");
                if (DataBaseDAL.BLL.IsDataBaseExist(2, databaseModel, ref msg))
                {
                    UppDateMsg("数据库存在，检测成功");
                    sfdBackUp.Filter = "备份文件(*.sqlDbBak)|*.sqlDbBak|所有文件(*.*)|*.*";
                    sfdBackUp.Title = "备份文件";
                    if (sfdBackUp.ShowDialog() == DialogResult.OK)
                    {
                        UppDateMsg("开始备份数据库");
                        backupPath = sfdBackUp.FileName;
                        if (DataBaseDAL.BLL.BackUpDataBase(2, databaseModel, backupPath, ref msg))
                        {
                            UppDateMsg("备份数据库成功");
                        }
                        else
                        {
                            UppDateMsg("备份数据库失败:" + msg);
                        }
                    }
                }
                else
                {
                    UppDateMsg("数据库不存在");
                }
            }
        }
 
        /// <summary>
        /// 恢复数据库 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnRestoreDB_Click(object sender, EventArgs e)
        {
            if (cmbDbName.Text == "")
            {
                MessageBox.Show("请先进行连接测试，获取数据库信息", "系统提示",
                                  MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            if (!IsBlank())
            {
                string msg = "";
                string RestorePath = "";
                GetDataBaseInfo(cmbDbName.Text);

                DataBaseDAL.DAL.ClearAllPool();

                UppDateMsg("开始检测数据库是否存在");
                if (DataBaseDAL.BLL.IsDataBaseExist(2, databaseModel, ref msg))
                {
                    UppDateMsg("数据库存在,检测成功");
                    OpenFileDialog ofdRestroeDb = new OpenFileDialog();
                    ofdRestroeDb.Filter = "备份文件(*.sqlDbBak)|*.sqlDbBak|所有文件(*.*)|*.*";
                    ofdRestroeDb.Title = "备份文件";
                    if (ofdRestroeDb.ShowDialog() == DialogResult.OK)
                    {
                        UppDateMsg("开始恢复数据库");
                        RestorePath = ofdRestroeDb.FileName;
                        if (DataBaseDAL.BLL.RestoreDataBaseByBackUp(2, databaseModel, RestorePath, ref msg))
                        {
                            UppDateMsg("恢复数据库成功");
                        }
                        else
                        {
                            UppDateMsg("恢复数据库失败:" + msg);

                        }
                    }
                }
                else
                {
                    UppDateMsg("数据库不存在");
                }
            }
        }

        /// <summary>
        /// 更新操作信息栏
        /// </summary>
        /// <param name="msg"></param>
        private void UppDateMsg(string msg)
        {
            if (string.IsNullOrEmpty(msg))
            {
                return;
            }
            else
            {
                if (this.txtStatusInfo.InvokeRequired)
                {
                    InitialControl delg = new InitialControl(UppDateMsg);
                    this.txtStatusInfo.Invoke(delg, new object[] { msg });
                }
                else
                {
                    txtStatusInfo.Text += DateTime.Now.ToLongTimeString() + "\t" + msg + "\r\n";
                }
            }
        }

        /// <summary>
        /// 文件滚动条移动
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void txtStatusInfo_TextChanged(object sender, EventArgs e)
        {
            txtStatusInfo.Select(txtStatusInfo.Text.Length, 0);
            txtStatusInfo.ScrollToCaret();
        }
 
        private void tslAccountAdmin_Click(object sender, EventArgs e)
        {
            AccountAdminFrame accountAdminFrame = new AccountAdminFrame();
            accountAdminFrame.ShowDialog();
        }
      
        private void tslPeripheryManualConfig_Click(object sender, EventArgs e)
        {
            PeripheralConfigFrame form = new PeripheralConfigFrame();
            form.ShowDialog();
        }

        /// <summary>
        /// 自动配置
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tslPeripheryAutoConfig_Click(object sender, EventArgs e)
        {
            PeripheraAutoConfigFrame form = new PeripheraAutoConfigFrame();
            form.ShowDialog();
        }
    }
}
